﻿#ifndef VIDEODEVICE_H
#define VIDEODEVICE_H

#include <QWidget>
#include <QTimer>
#include <QDebug>
#include <QReadWriteLock>

#include <QCameraViewfinderSettings>
#include <QVideoProbe>
#include <QVideoFrame>
#include <QCameraViewfinder>
#include <QCameraInfo>
#include <QCamera>

#define VIDEO_FPS               (30)

#define CAMERA_PIXEL_WIDE       (1920)
#define CAMERA_PIXEL_HIGH       (1080)

class VideoDevice : public QWidget
{
    Q_OBJECT
public:
    explicit VideoDevice(QSize showSize, QWidget *parent = nullptr);
    ~VideoDevice(void);

    void openCamera(bool reboot = false);
    void closeCamera(void);

    void showViewfinder(int x, int y);
    void hideViewfinder(void) { if (m_viewFinder != nullptr) m_viewFinder->hide(); }
    //获取摄像头配置参数
    int getFrameRate(void) { return VIDEO_FPS; }
    QSize getPixelSize(void) { return QSize(CAMERA_PIXEL_WIDE, CAMERA_PIXEL_HIGH);}
    //获取每帧数据
    void getFrameData(void * pData);
    void getFrameData(QByteArray & pArray);

public slots:
    void setProbeStatus(bool status) { m_probeStatus = status; }

private:
    void setCamera(const QCameraInfo &cameraInfo);

private slots:
    void updateCameraState(QCamera::State);
    void showCameraError(void);
    void onProbeFrameSlot(const QVideoFrame &frame);
    void cameraTimeoutSlot(void);

signals:
    void videoFrameSingal(void);

private:
    QCamera * m_camera;
    QVideoProbe * m_videoProbe;
    QCameraViewfinder * m_viewFinder = nullptr;

    QTimer * m_cameraTimer = nullptr;
    QByteArray * m_frameData;
    QReadWriteLock m_frameRWLock;

    int m_cameraCnt = 0;
    bool isCameraOpen = false;
    bool m_probeStatus = false;
};

#endif // VIDEODEVICE_H
